<template>
  <el-dialog
    :model-value="visible"
    @update:model-value="$emit('close')"
    title="分类管理"
    width="600px"
    :close-on-click-modal="false"
  >
    <div class="category-manager">
      <!-- 当前分类列表 -->
      <div class="category-list">
        <h4>当前分类</h4>
        <div class="categories-grid">
          <div
            v-for="category in categories"
            :key="category.id"
            class="category-item"
            :class="{ 'system-category': category.isSystem }"
          >
            <div class="category-info">
              <el-icon class="category-icon" :color="category.color">
                <component :is="getCategoryIcon(category.icon)" />
              </el-icon>
              <div class="category-details">
                <div class="category-name">{{ category.name }}</div>
                <div class="category-count">{{ getCategoryCount(category.id) }} 个账号</div>
              </div>
            </div>
            <div class="category-actions" v-if="!category.isSystem">
              <el-button size="small" type="text" @click="editCategory(category)">
                <el-icon><Edit /></el-icon>
              </el-button>
              <el-button 
                size="small" 
                type="text" 
                @click="deleteCategory(category)"
                :disabled="getCategoryCount(category.id) > 0"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
            <div class="system-badge" v-if="category.isSystem">
              系统分类
            </div>
          </div>
        </div>
      </div>

      <!-- 添加新分类 -->
      <div class="add-category">
        <h4>添加新分类</h4>
        <el-card class="new-category-card">
          <div class="new-category-form">
            <div class="form-row">
              <div class="form-item">
                <label>分类名称</label>
                <el-input
                  v-model="newCategory.name"
                  placeholder="输入分类名称"
                  maxlength="10"
                  show-word-limit
                />
              </div>
              <div class="form-item">
                <label>分类颜色</label>
                <el-color-picker v-model="newCategory.color" />
              </div>
            </div>
            
            <div class="form-item">
              <label>分类图标</label>
              <div class="icon-selector">
                <div 
                  v-for="icon in availableIcons" 
                  :key="icon.name"
                  class="icon-option"
                  :class="{ active: newCategory.icon === icon.name }"
                  @click="newCategory.icon = icon.name"
                >
                  <el-icon :color="newCategory.color">
                    <component :is="icon.component" />
                  </el-icon>
                  <span>{{ icon.label }}</span>
                </div>
              </div>
            </div>
            
            <div class="form-actions">
              <el-button @click="resetForm">重置</el-button>
              <el-button 
                type="primary" 
                @click="addCategory"
                :disabled="!newCategory.name.trim()"
              >
                添加分类
              </el-button>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 分类预设模板 -->
      <div class="category-templates">
        <h4>快速添加</h4>
        <div class="templates-grid">
          <div
            v-for="template in categoryTemplates"
            :key="template.id"
            class="template-item"
            @click="addFromTemplate(template)"
          >
            <el-icon :color="template.color">
              <component :is="getCategoryIcon(template.icon)" />
            </el-icon>
            <span>{{ template.name }}</span>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="$emit('close')">关闭</el-button>
        <el-button type="primary" @click="saveCategories">保存设置</el-button>
      </div>
    </template>

    <!-- 编辑分类对话框 -->
    <el-dialog
      v-model="showEditDialog"
      title="编辑分类"
      width="400px"
      append-to-body
    >
      <div class="edit-category-form" v-if="editingCategory">
        <div class="form-item">
          <label>分类名称</label>
          <el-input
            v-model="editingCategory.name"
            placeholder="输入分类名称"
            maxlength="10"
            show-word-limit
          />
        </div>
        
        <div class="form-row">
          <div class="form-item">
            <label>分类颜色</label>
            <el-color-picker v-model="editingCategory.color" />
          </div>
        </div>
        
        <div class="form-item">
          <label>分类图标</label>
          <div class="icon-selector">
            <div 
              v-for="icon in availableIcons" 
              :key="icon.name"
              class="icon-option"
              :class="{ active: editingCategory.icon === icon.name }"
              @click="editingCategory.icon = icon.name"
            >
              <el-icon :color="editingCategory.color">
                <component :is="icon.component" />
              </el-icon>
            </div>
          </div>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showEditDialog = false">取消</el-button>
          <el-button type="primary" @click="saveEditedCategory">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { useAccountsStore } from '../stores/accounts'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Edit, Delete, Operation, User, Key, Monitor, VideoPlay, 
  Handbag, ChatDotRound, CreditCard, Star, Setting,
  Document, Location
} from '@element-plus/icons-vue'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['close', 'categories-updated'])

const accountsStore = useAccountsStore()
const showEditDialog = ref(false)
const editingCategory = ref(null)

// 默认系统分类
const defaultCategories = [
  { id: 'work', name: '工作', icon: 'Operation', color: '#409EFF', isSystem: true },
  { id: 'personal', name: '个人', icon: 'User', color: '#67C23A', isSystem: true },
  { id: 'social', name: '社交媒体', icon: 'ChatDotRound', color: '#E6A23C', isSystem: true },
  { id: 'finance', name: '金融理财', icon: 'CreditCard', color: '#F56C6C', isSystem: true },
  { id: 'entertainment', name: '游戏娱乐', icon: 'VideoPlay', color: '#909399', isSystem: true },
  { id: 'shopping', name: '购物网站', icon: 'Handbag', color: '#FF6B9D', isSystem: true }
]

// 用户自定义分类
const customCategories = ref([])

// 所有分类
const categories = computed(() => {
  return [...defaultCategories, ...customCategories.value]
})

// 新分类表单
const newCategory = ref({
  name: '',
  icon: 'Star',
  color: '#409EFF'
})

// 可用图标
const availableIcons = [
  { name: 'Star', component: Star, label: '星星' },
  { name: 'Setting', component: Setting, label: '设置' },
  { name: 'Document', component: Document, label: '文档' },
  { name: 'Location', component: Location, label: '位置' },
  { name: 'Key', component: Key, label: '密钥' },
  { name: 'Monitor', component: Monitor, label: '电脑' },
  { name: 'CreditCard', component: CreditCard, label: '卡片' },
  { name: 'User', component: User, label: '用户' },
  { name: 'Operation', component: Operation, label: '操作' },
  { name: 'VideoPlay', component: VideoPlay, label: '视频' },
  { name: 'Handbag', component: Handbag, label: '购物' },
  { name: 'ChatDotRound', component: ChatDotRound, label: '聊天' }
]

// 分类模板
const categoryTemplates = [
  { id: 'education', name: '教育学习', icon: 'Document', color: '#722ED1' },
  { id: 'travel', name: '旅行出行', icon: 'Location', color: '#13C2C2' },
  { id: 'health', name: '健康医疗', icon: 'Star', color: '#52C41A' },
  { id: 'food', name: '美食餐饮', icon: 'Setting', color: '#FA8C16' },
  { id: 'photography', name: '摄影图片', icon: 'Monitor', color: '#EB2F96' },
  { id: 'design', name: '设计创作', icon: 'Operation', color: '#9C27B0' }
]

// 获取分类图标组件
const getCategoryIcon = (iconName) => {
  const iconMap = {
    Operation, User, ChatDotRound, CreditCard, VideoPlay, Handbag,
    Star, Setting, Document, Location, Key, Monitor
  }
  return iconMap[iconName] || Star
}

// 获取分类下的账号数量
const getCategoryCount = (categoryId) => {
  return accountsStore.accounts.filter(account => account.category === categoryId).length
}

// 重置表单
const resetForm = () => {
  newCategory.value = {
    name: '',
    icon: 'Star',
    color: '#409EFF'
  }
}

// 添加新分类
const addCategory = () => {
  if (!newCategory.value.name.trim()) {
    ElMessage.warning('请输入分类名称')
    return
  }
  
  // 检查名称是否重复
  const exists = categories.value.some(cat => cat.name === newCategory.value.name.trim())
  if (exists) {
    ElMessage.warning('分类名称已存在')
    return
  }
  
  const category = {
    id: `custom_${Date.now()}`,
    name: newCategory.value.name.trim(),
    icon: newCategory.value.icon,
    color: newCategory.value.color,
    isSystem: false
  }
  
  customCategories.value.push(category)
  resetForm()
  ElMessage.success('分类添加成功')
}

// 从模板添加
const addFromTemplate = (template) => {
  // 检查是否已存在
  const exists = categories.value.some(cat => cat.name === template.name)
  if (exists) {
    ElMessage.warning('该分类已存在')
    return
  }
  
  const category = {
    id: `custom_${Date.now()}`,
    name: template.name,
    icon: template.icon,
    color: template.color,
    isSystem: false
  }
  
  customCategories.value.push(category)
  ElMessage.success(`已添加 ${template.name} 分类`)
}

// 编辑分类
const editCategory = (category) => {
  editingCategory.value = { ...category }
  showEditDialog.value = true
}

// 保存编辑的分类
const saveEditedCategory = () => {
  if (!editingCategory.value.name.trim()) {
    ElMessage.warning('请输入分类名称')
    return
  }
  
  // 检查名称是否与其他分类重复
  const exists = categories.value.some(cat => 
    cat.id !== editingCategory.value.id && cat.name === editingCategory.value.name.trim()
  )
  if (exists) {
    ElMessage.warning('分类名称已存在')
    return
  }
  
  const index = customCategories.value.findIndex(cat => cat.id === editingCategory.value.id)
  if (index !== -1) {
    customCategories.value[index] = { ...editingCategory.value }
    ElMessage.success('分类更新成功')
  }
  
  showEditDialog.value = false
  editingCategory.value = null
}

// 删除分类
const deleteCategory = async (category) => {
  const count = getCategoryCount(category.id)
  if (count > 0) {
    ElMessage.warning(`该分类下还有 ${count} 个账号，无法删除`)
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除分类"${category.name}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const index = customCategories.value.findIndex(cat => cat.id === category.id)
    if (index !== -1) {
      customCategories.value.splice(index, 1)
      ElMessage.success('分类删除成功')
    }
  } catch {
    // 用户取消删除
  }
}

// 保存分类设置
const saveCategories = () => {
  // 保存到本地存储
  localStorage.setItem('customCategories', JSON.stringify(customCategories.value))
  emit('categories-updated', categories.value)
  ElMessage.success('分类设置已保存')
}

// 加载自定义分类
const loadCustomCategories = () => {
  try {
    const saved = localStorage.getItem('customCategories')
    if (saved) {
      customCategories.value = JSON.parse(saved)
    }
  } catch (error) {
    console.error('加载自定义分类失败:', error)
    customCategories.value = []
  }
}

// 监听对话框显示状态
watch(() => props.visible, (visible) => {
  if (visible) {
    loadCustomCategories()
  }
})

// 初始化
loadCustomCategories()
</script>

<style scoped>
.category-manager {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.category-manager h4 {
  margin: 0 0 16px 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
}

.categories-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}

.category-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px;
  border: 1px solid #e6e6e6;
  border-radius: 8px;
  background: white;
  transition: all 0.3s ease;
}

.category-item:hover {
  border-color: #409EFF;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

.system-category {
  background: #f8f9fa;
  border-color: #dee2e6;
}

.category-info {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
}

.category-icon {
  font-size: 20px;
}

.category-name {
  font-weight: 500;
  color: #333;
}

.category-count {
  font-size: 12px;
  color: #666;
}

.category-actions {
  display: flex;
  gap: 4px;
}

.system-badge {
  font-size: 10px;
  color: #999;
  background: #f0f0f0;
  padding: 2px 6px;
  border-radius: 3px;
}

.new-category-card {
  border: 2px dashed #d9d9d9;
  background: #fafafa;
}

.new-category-form {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr auto;
  gap: 16px;
  align-items: end;
}

.form-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-item label {
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.icon-selector {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  gap: 8px;
}

.icon-option {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
  padding: 8px;
  border: 1px solid #e6e6e6;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.icon-option:hover {
  border-color: #409EFF;
  background: #f0f9ff;
}

.icon-option.active {
  border-color: #409EFF;
  background: #e6f7ff;
  color: #409EFF;
}

.icon-option span {
  font-size: 10px;
  color: #666;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.templates-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 8px;
}

.template-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  padding: 12px;
  border: 1px solid #e6e6e6;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.template-item:hover {
  border-color: #409EFF;
  background: #f0f9ff;
  transform: translateY(-2px);
}

.template-item span {
  font-size: 12px;
  color: #666;
}

.edit-category-form {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
